package day021.homework.p8;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashSet;

public class DownloadThread extends Thread {
    HashSet<String> ips = new HashSet<>();

    private Socket socket;

    public DownloadThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            OutputStream netOutput = socket.getOutputStream();
            FileInputStream fis = new FileInputStream("D:\\ideaProjects\\javase_code\\study-practice\\" +
                    "src\\day021\\tcp\\files\\123.jpg");

            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1) {
                netOutput.write(buf, 0, len);
            }

            socket.shutdownOutput();

            String ip = socket.getInetAddress().getHostAddress();
            if (ips.add(ip)) {
                System.out.println("恭喜" + ip + "恭喜，下载成功！！ 当前下载的人数是：" + ips.size());
            }
            fis.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
